<?php

namespace App\Listeners;

use Illuminate\DatabaseEvents\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

use Log;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle($event)
    {
        if (env('APP_ENV', 'production') == 'local') {
            $sql = str_replace("?", "'%s'", $event->sql);
            $log = vsprintf($sql, $event->bindings);
            $update = '/^update/';
            $delete = '/^delete/';
            if(preg_match($update,$log)) {
                file_put_contents(storage_path('logs/sql/updateSql.log'), "[".date("Y-m-d H:i:s")."]　SQL.INFO：".$_SERVER['REQUEST_URI']."　用户ID：".session("uid")."　执行sql语句：".$log."\n", FILE_APPEND);
            }elseif(preg_match($delete,$log)){
                file_put_contents(storage_path('logs/sql/deleteSql.log'), "[".date("Y-m-d H:i:s")."]　SQL.INFO：　用户ID：".session("uid")."　执行sql语句：".$log."\n", FILE_APPEND);
            }
        }
    }
}
